package com.itany.cloud.route;

import jakarta.validation.constraints.NotNull;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.function.Predicate;

/**
 * @author 石小俊
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    /**
     * @param config
     * @return
     */
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            /**
             * @param serverWebExchange Gateway封装的用于获取web资源的对象
             * @return
             */
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                // 获取请求对象
                ServerHttpRequest request = serverWebExchange.getRequest();
                // 获取响应对象
                ServerHttpResponse response = serverWebExchange.getResponse();
                // 当前的路由用于实现判断请求参数
                String type = request.getQueryParams().getFirst("type");
                if (type == null)
                    return false;
                if (type.equals(config.getType())) {
                    return true;
                }
                return false;
            }
        };
    }

    public static class Config {
        @NotNull
        private String type;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }

}
